package com.hhsjdesign.dynamicui.businessdata

import com.hhsjdesign.dynamicui.businessdata.IViewable.*
import com.hhsjdesign.dynamicui.utils.ClassCachePool
import org.json.JSONObject
import java.lang.reflect.Method

/**
 * 业务数据模型，组件自带数据，一般都是菜单
 */
object BusinessDataParser {

    fun createData(
        business: String,
        parentId: String?,
        treeId: String?,
        jo2: JSONObject
    ): IViewableTransformer? {
        val clazz: Class<*>? =
            ClassCachePool.getClassByWidgetType(ClassCachePool.BUSINESS_BEAN, business)
        var method: Method? = clazz?.getDeclaredMethod(
            "fromJSON",
            String::class.java,
            String::class.java,
            JSONObject::class.java
        )
        method?.let {
            it.isAccessible = true
            return (it.invoke(null, parentId, treeId, jo2) as? IViewableTransformer)
        }
        method = clazz?.getDeclaredMethod(
            "fromJSON",
            JSONObject::class.java
        )
        method?.let {
            it.isAccessible = true
            return (it.invoke(null, jo2) as? IViewableTransformer).apply {
                if (this is IRedDotTree) {
                    this.treeId(parentId, treeId)
                }
            }
        }

        return null
    }

    @JvmStatic
    fun mapSize(): Int {
        return ClassCachePool.businessDataSize()
    }

}